// pages/activity/activity.js
const {
    getActivity,
    searchActivity,
} = require('../../services/activityReq');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        searchPageNum: 1,
        pageSize: 10,
        searchList: [],
        // 监听是否加载完毕
        isSearchFinish: false,
        searchValue: '',
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onShow() {
        // 获取所有活动
        this.setData({
            searchList: [],
            isSearchFinish: false,
            searchValue: '',
            searchPageNum: 1,
            pageSize: 10,
        })
        this.handleGetAllActivity();
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        this.setData({
            searchPageNum: this.data.searchPageNum + 1
        })
        this.handleGetAllActivity();
    },
    // 获取全部活动
    handleGetAllActivity() {
        this.handleSearchActivity()
    },

    // 搜索更新
    handleSearchChange(e) {
        this.setData({
            searchValue: e.detail,
            searchList: [],
            searchPageNum: 1,
            isSearchFinish: false,
        });
    },

    // 搜索活动
    handleSearchActivity() {
        if (this.data.isSearchFinish) return;
        wx.showLoading({
            title: '加載中',
        });
        return searchActivity(this.data.searchValue, this.data.searchPageNum, this.data.pageSize, res => {
            if (res.data.code !== 0) {
                return wx.showToast({
                    title: res.data.msg,
                    icon: 'error',
                });
            }
            let list = res.data.data.list;
            list?.forEach((v, i) => {
                v.activityDatetime = wx.$moment(v.activityDatetime).format('YYYY-MM-DD');
                try {
                    v.activityAddress = JSON.parse(v.activityAddress).address;
                } catch (e) {}
            });
            let searchList = this.data.searchList
            this.setData({
                searchList: [...searchList, ...list],
            });
            if (list.length < this.data.pageSize) {
                this.setData({
                    isSearchFinish: true,
                });
            }
            return this.handleRestore();
        });
    },
    handleRestore() {
        wx.hideLoading()
    },
    // 跳转活动详情
    handleGoDetail(e) {
        const id = e.detail;
        wx.navigateTo({
            url: `/pages/activityDetail/activityDetail?id=${id}`,
        });
    },
});